//
//  YKAddTagViewController.m
//  baisi
//
//  Created by 吴高烽 on 2016/11/3.
//  Copyright © 2016年 吴高烽. All rights reserved.
//

#import "YKAddTagViewController.h"
#import "YKTagTextField.h"
#import "YKTagButton.h"
@interface YKAddTagViewController ()<UITextFieldDelegate>
/** 内容 */
@property (nonatomic ,weak)UIView *contentView;
/** 文本输入框 */
@property (nonatomic ,weak)YKTagTextField *textField;
/** 添加按钮 */
@property (nonatomic ,weak)UIButton *addButton;
/** 所有标签按钮 */
@property (nonatomic ,strong)NSMutableArray *tagButtons;

@end

@implementation YKAddTagViewController
#pragma mark- 懒加载
-(NSMutableArray *)tagButtons{
    if (!_tagButtons) {
        _tagButtons = [NSMutableArray array];
    }
    return _tagButtons ;
}
-(UIButton *)addButton{
    if (!_addButton) {
        UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
        addButton.width = self.contentView.width ;
        addButton.height = 35 ;
        [addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [addButton addTarget:self action:@selector(addButtonClick) forControlEvents:UIControlEventTouchUpInside];
        addButton.titleLabel.font = YKTagFont ;
        addButton.contentEdgeInsets = UIEdgeInsetsMake(0, YKTagButtonMargin, 0, YKTagButtonMargin);
        addButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft ;
//        addButton.backgroundColor = YKGlobalBackgroundColor ;
        addButton.backgroundColor = [UIColor blueColor];
        [self.contentView addSubview:addButton];
        _addButton = addButton ;
    }
    return _addButton ;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNav];
    [self setuContentView];
    [self setupTextFiled];
    [self setupTags];
    
}

-(void)log:(UIButton*)btn{
    NSLog(@"123456");
}
-(void)setupTags{
    for (NSString *tag in self.tags) {
        self.textField.text = tag ;
        [self addButtonClick];
    }
    self.tags = nil ;
}
-(void)setupTextFiled{
     __weak typeof(self) weakSelf = self;
    YKTagTextField *textField = [[YKTagTextField alloc]init];
    textField.width = self.contentView.width ;
    textField.deleteBlock = ^{
        if (weakSelf.textField.hasText) {
            return ;
        }
        [weakSelf tagButtonClick:[weakSelf.tagButtons lastObject]];
    };
    textField.delegate = self ;
    [textField addTarget:self action:@selector(textDidChange) forControlEvents:UIControlEventEditingChanged];
    [textField becomeFirstResponder];
    [self.contentView addSubview:textField];
    self.textField = textField ;
}
-(void)setuContentView{
    UIView *contentView = [[UIView alloc]init];
    contentView.x = YKTagButtonMargin ;
    contentView.width = self.view.width - 2 * contentView.x ;
    contentView.y = 64 + YKTagButtonMargin ;
    contentView.height = SCHeight ;
    [self.view addSubview: contentView];
    self.contentView = contentView ;
}
-(void)setupNav{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"添加标签";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(done:)];
    
}
-(void)done:(UIButton*)btn{
//    传递数据给上一个控制器
//    NSMutableArray *tags = [NSMutableArray array];
//    for (YKTagButton *btn in self.tagButtons) {
//        [tags addObject:btn.currentTitle];
//    }
//    利用kvc将button中的内容取出来
    NSArray *tags = [self.tagButtons valueForKeyPath:@"currentTitle"];
    ! self.tagsBlock ? : self.tagsBlock(tags);
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)tagButtonClick:(YKTagButton*)tagButton{
    [tagButton removeFromSuperview];
    [self.tagButtons removeObject:tagButton];
    [UIView animateWithDuration:0.25 animations:^{
        [self updateTagButtonFrame];
        [self updateTextFieldFrame];
    }];
}
-(void)addButtonClick{
    if (self.tagButtons.count == 5) {
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        [SVProgressHUD showErrorWithStatus:@"最多只能添加5个标签"];
        return ;
    }
    YKTagButton *tagButton = [YKTagButton buttonWithType:UIButtonTypeCustom];
    [tagButton addTarget:self action:@selector(tagButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [tagButton setTitle:self.textField.text forState:UIControlStateNormal];
    [self.contentView addSubview:tagButton];
    [self.tagButtons addObject:tagButton];
    self.textField.text = nil ;
    self.addButton.hidden = YES ;
    [self updateTagButtonFrame];
    [self updateTextFieldFrame];
}
-(void)textDidChange{
    if (self.textField.hasText) {
        self.addButton.hidden = NO ;
        self.addButton.y = CGRectGetMaxY(self.textField.frame) + YKTagButtonMargin ;
        [self.addButton setTitle:[NSString stringWithFormat:@"添加标签: %@",self.textField.text] forState:UIControlStateNormal];
        NSString *text = self.textField.text ;
        NSUInteger len = text.length ;
        NSString *lastLetter = [text substringFromIndex:len - 1];
        if ([lastLetter isEqualToString:@","] || [lastLetter isEqualToString:@", "]) {
            self.textField.text = [text substringToIndex:len - 1];
            [self addButtonClick];
        }
    }else{
        self.addButton.hidden = YES ;
    }
}
-(void)updateTagButtonFrame{
    for (NSInteger i = 0 ; i < self.tagButtons.count ; i++) {
        YKTagButton *tagButton = self.tagButtons[i];
        if (i == 0) {
            tagButton.x = 0 ;
            tagButton.y = 0 ;
        }else{
            YKTagButton *lastTagButton = self.tagButtons[i-1];
            CGFloat leftWidth = CGRectGetMaxX(lastTagButton.frame) + YKTagButtonMargin ;
            CGFloat rightWidth = self.contentView.width - leftWidth ;
            if (rightWidth >= tagButton.width) {
                tagButton.y = lastTagButton.y;
                tagButton.x = leftWidth ;
            }else{
                tagButton.x = 0 ;
                tagButton.y = CGRectGetMaxY(lastTagButton.frame ) + YKTagButtonMargin ;
            }
        }
        
    }

}
-(void)updateTextFieldFrame{
    YKTagButton *lastTagButton = [self.tagButtons lastObject];
    CGFloat leftWidth = CGRectGetMaxX(lastTagButton.frame) + YKTagButtonMargin ;
    if (self.contentView.width - leftWidth >= [self textFieldTextWidth]) {
        self.textField.y = lastTagButton.y;
        self.textField.x = leftWidth ;
    }else{
        self.textField.x = 0 ;
        self.textField.y = CGRectGetMaxY(lastTagButton.frame) + YKTagButtonMargin ;
    }
}
/**
 * textField的文字宽度
 */
- (CGFloat)textFieldTextWidth
{
    CGFloat textW = [self.textField.text sizeWithAttributes:@{NSFontAttributeName : self.textField.font}].width;
    return MAX(100, textW);
}
#pragma mark - <UITextFieldDelegate>
/**
 * 监听键盘最右下角按钮的点击（return key， 比如“换行”、“完成”等等）
 */
- (BOOL)textFieldShouldReturn:(YKTagTextField *)textField
{
    if (textField.hasText) {
        [self addButtonClick];
    }
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
